import { Component, OnInit } from '@angular/core';

import {HomeService} from "./home.service";

import {HeroObject} from "../model/heroObject";

//@Component 是个装饰器函数，用于为该组件指定 Angular 所需的元数据。
@Component({
  selector: 'app-home',  //组件的选择器,用来在父组件的模板中匹配 HTML 元素的名称，以识别出该组件。
  templateUrl: './home.component.html', //组件模板文件的位置
  styleUrls: ['./home.component.css'],  //组件私有 CSS 样式表文件的位置
  providers :[HomeService],
})
export class HomeComponent implements OnInit {

  heros :HeroObject[];

 // selectHero : HeroObject;

  constructor(private heroService:HomeService) {

  }

  //生命周期的初始化逻辑
  ngOnInit() {
    //加载网络数据
    this.loadHerosList();
  }

   //获取数据
  loadHerosList() : void{

    //subscribe 函数把这个英雄数组传给这个回调函数
    this.heroService.getHeroList().subscribe(herolist =>this.heros = herolist);
  }

  // //点击英雄事件
  // clickHeroEvent(hero : HeroObject) : void{
  //   this.selectHero = hero;
  // }

  //新增英雄处理事件
  addHeroEvent(name : string):void{
    name = name.trim();
    if(!name) return;

    let  heroObject : HeroObject = new HeroObject();
    heroObject.id = this.heros.length + 1;
    heroObject.type = "新增";
    heroObject.name = name;

    console.log(heroObject);
    this.heroService.addHeroEvent(heroObject).subscribe(
     hero =>{this.heros.push(hero);}
    );
  }
  //删除英雄
  deleteHero(hero : HeroObject) :void{

    this.heros = this.heros.filter(h => h !== hero);

    this.heroService.deleteHeroEvent(hero).subscribe();
  }

}
